<template>
  <div v-if="user.role=='ADMIN'">
    <div class="search">
      <el-input placeholder="请输入账号查询" style="width: 200px" v-model="username"></el-input>
      <el-input placeholder="请输入姓名查询" style="width: 200px;margin-left: 10px" v-model="name"></el-input>
      <el-button type="info" plain style="margin-left: 10px" @click="load(1)">查询</el-button>
      <el-button type="warning" plain style="margin-left: 10px" @click="reset">重置</el-button>
    </div>

    <div class="operation">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
      <el-button type="success" plain @click="exportData">批量导出</el-button>
      <!-- <el-button type="success" plain @click="syncStaff">同步OA人员信息</el-button> -->
      <!--      <el-button type="success" plain-->
      <!--                 @click="syncStaff"-->
      <!--                 :loading="isSyncing"-->
      <!--                 :disabled="isSyncing">同步OA人员信息-->
      <!--      </el-button>-->
    </div>

    <div class="table">
      <el-table :data="tableData" row-key="id" strip @selection-change="handleSelectionChange">
        <el-table-column type="selection" :reserve-selection="true" width="55" align="center"></el-table-column>
        <el-table-column label="序号" width="70" align="center" sortable>
          <template v-slot='scope'>
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>

        <el-table-column prop="username" label="账号">
          <template v-slot="scope">
            <el-tag v-if="scope.row.username === user.username" type="info">{{ scope.row.username }}</el-tag>
            <span v-else>{{ scope.row.username }}</span>
          </template>
        </el-table-column>
        <!--        <el-table-column label="密码">-->
        <!--          <template v-slot="scope">-->
        <!--            ******** &lt;!&ndash; 密码不显示明文 &ndash;&gt;-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column prop="departmentName" label="部门"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="phone" label="电话"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="workCode" width="175%" label="工号"></el-table-column>

        <el-table-column label="头像">
          <template v-slot="scope">
            <div style="display: flex; align-items: center">
              <el-image style="width: 40px; height: 40px; border-radius: 50%" v-if="scope.row.avatar"
                        :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]"></el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="role" label="角色">
          <template v-slot="scope">
            <el-tag type="info" v-if="scope.row.role === 'ADMIN'">{{ formatRole(scope.row.role) }}</el-tag>
            <span v-if="scope.row.role === 'STAFF'">{{ formatRole(scope.row.role) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template v-slot="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" circle @click="handleEdit(scope.row)"></el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" circle @click="del(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
            background
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next"
            :total="total">
        </el-pagination>
      </div>
    </div>


    <el-dialog title="员工信息" :visible.sync="fromVisible" width="40%" :close-on-click-modal="false" destroy-on-close>
      <el-form :model="form" label-width="100px" style="padding-right: 50px" :rules="rules" ref="formRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" :placeholder="form.id ? '留空则不修改密码' : '默认密码：123456'"></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="departmentName">
          <el-select ref="selectTree" v-model="form.departmentId" filterable="true" clearable style="width: 100%;">
            <el-option
                v-for="item in departmentList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
                style="display: none;"/>
            <el-tree
                :data="departmentTree"
                :props="{children: 'children', label: 'name'}"
                highlight-current
                @node-click="handleNodeClick"
                default-expand-all/>
          </el-select>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" placeholder="电话"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="邮箱"></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
              class="avatar-uploader"
              :action="$baseUrl + '/files/upload'"
              :headers="{ token: user.token }"
              list-type="picture"
              :on-success="handleAvatarSuccess"
          >
            <el-button type="primary">上传头像</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="请选择角色">
            <el-option label="管理员" value="ADMIN"></el-option>
            <el-option label="普通员工" value="STAFF"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="fromVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { saveAs } from 'file-saver';
export default {
  name: "Admin",
  data() {
    return {
      tableData: [],  // 所有的数据
      pageNum: 1,   // 当前的页码
      pageSize: 10,  // 每页显示的个数
      total: 0,
      username: null,
      name: null,
      fromVisible: false,
      form: {},
      departmentList: [],
      departmentTree: [],
      isSyncing: false,// 控制同步按钮的加载状态，默认为 false
      user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
      rules: {
        username: [
          {required: true, message: '请输入账号', trigger: 'blur'},
        ]
      },
      ids: []
    }
  },
  created() {
    this.load(1)
  },
  methods: {
    formatRole(role) {
      return role === 'ADMIN' ? '管理员' : '普通员工';
    },//同步OA人员信息按钮的实现方法
    // syncStaff() {
    //     // 弹出一个确认框，防止误操作
    //     this.$confirm('此操作将从泛微OA同步人员信息，覆盖现有数据并新增不存在的人员，是否继续?', '提示', {
    //       confirmButtonText: '确定',
    //       cancelButtonText: '取消',
    //       type: 'warning'
    //     }).then(() => {
    //       // 用户点击确定后，调用后端接口
    //       this.$request.get('/staff/sync-from-oa').then(res => {
    //         if (res.code === '200') {
    //           // 同步成功，给出提示并刷新表格数据
    //           this.$message.success('人员信息同步成功！');
    //           this.load(); // 假设你有一个方法用于重新加载表格数据
    //         } else {
    //           // 同步失败，显示错误信息
    //           this.$message.error(res.msg);
    //         }
    //       }).catch(err => {
    //         // 请求失败，例如网络错误等
    //         this.$message.error('同步失败，请检查网络或后端服务');
    //         console.error('同步请求出错:', err);
    //       });
    //     }).catch(() => {
    //       // 用户点击取消，不执行任何操作
    //       this.$message.info('已取消同步');
    //     });
    //   },

    async syncStaff() {
      this.$confirm('此操作将从泛微OA同步人员信息，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 用户点击确定后，开始同步
        this.isSyncing = true; // 1. 开启加载状态

        try {
          // 2. 调用后端接口，使用 await 等待同步完成
          const res = await this.$request.get('/staff/sync-from-oa');

          if (res.code === '200') {
            // 3. 同步成功，给出提示并刷新表格
            this.$message.success('人员信息同步成功！');
            this.load();
          } else {
            // 4. 同步失败，显示错误信息
            this.$message.error(res.msg);
          }
        } catch (err) {
          // 5. 请求失败或发生异常
          this.$message.error('同步失败，请检查网络或后端服务');
          console.error('同步请求出错:', err);
        } finally {
          // 6. 无论成功或失败，最后都要关闭加载状态
          this.isSyncing = false;
        }
      }).catch(() => {
        // 用户点击取消
        this.$message.info('已取消同步');
      });
    },

    // 假设这是你用于加载表格数据的方法
    // load() {
    //   // ...
    // }
    handleAdd() {   // 新增数据
      this.form = {
        role: 'STAFF',  // 默认角色设置为普通员工
        password: '123456' // 设置默认密码
      }
      this.fromVisible = true   // 打开弹窗
    },
    handleEdit(row) {   // 编辑数据
      this.form = JSON.parse(JSON.stringify(row))  // 给form对象赋值  注意要深拷贝数据
      this.form.password = '' // 编辑时清空密码字段，避免直接修改
      // 先查出扁平的部门数组
      this.$request.get('/department/selectAll').then(res => {
        this.departmentList = res.data
      })
      // 再查出树形的部门数组
      this.$request.get('/department/selectTree').then(res => {
        this.departmentTree = res.data
      })
      this.fromVisible = true   // 打开弹窗
    },
    handleNodeClick(node) {
      this.$set(this.form, 'departmentId', node.id)
      this.$refs.selectTree.blur()
    },
    save() {   // 保存按钮触发的逻辑  它会触发新增或者更新
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // 如果是编辑且密码为空，则删除密码字段
          if (this.form.id && !this.form.password) {
            delete this.form.password
          }
          if (this.form.role === 'ADMIN') {

            setTimeout(() => {
              this.$message.warning('warning：通常管理员角色不能被修改！')
            }, 1000)
          }

          this.$request({
            url: this.form.id ? '/staff/update' : '/staff/add',
            method: this.form.id ? 'PUT' : 'POST',
            data: this.form
          }).then(res => {
            if (res.code === '200') {  // 表示成功保存
              this.$message.success('保存成功')
              this.load(1)
              this.fromVisible = false
            } else {
              this.$message.error(res.msg)  // 弹出错误的信息
            }
          })
        }
      })
    },
    del(id) {   // 单个删除
      this.$confirm('您确定删除吗？', '确认删除', {type: "warning"}).then(response => {
        this.$request.delete('/staff/delete/' + id).then(res => {
          if (res.code === '200') {   // 表示操作成功
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)  // 弹出错误的信息
          }
        })
      }).catch(() => {
      })
    },
    handleSelectionChange(rows) {   // 当前选中的所有的行数据
      this.ids = rows.map(v => v.id)
    },
    delBatch() {   // 批量删除
      if (!this.ids.length) {
        this.$message.warning('请选择数据')
        return
      }
      this.$confirm('您确定批量删除这些数据吗？', '确认删除', {type: "warning"}).then(response => {
        this.$request.delete('/staff/delete/batch', {data: this.ids}).then(res => {
          if (res.code === '200') {   // 表示操作成功
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)  // 弹出错误的信息
          }
        })
      }).catch(() => {
      })
    },
    load(pageNum) {  // 分页查询
      if (pageNum) this.pageNum = pageNum
      this.$request.get('/staff/selectPage', {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          username: this.username,
          name: this.name,
        }
      }).then(res => {
        this.tableData = res.data?.list
        this.total = res.data?.total
      })
    },
    exportData() {
      function extractFileName(disposition) {
        if (!disposition) return fallbackFileName();   // 关键兜底

        // 1. 先尝试 filename*=UTF-8''xxx
        const utf8Name = /filename\*=UTF-8''(.+)/i.exec(disposition);
        if (utf8Name) return decodeURIComponent(utf8Name[1]);

        // 2. 再尝试普通 filename="xxx" 或 filename=xxx
        const name = /filename=(?:''|")?([^;]+)(?:''|")?/i.exec(disposition);
        if (name) return decodeURIComponent(name[1].trim());

        return fallbackFileName();                     // 解析失败也兜底
      }
      /* 统一兜底：员工信息_yyyy-MM-dd_HHmm.xlsx */
      function fallbackFileName() {
        const now = new Date();
        const pad = n => String(n).padStart(2, '0');
        const dateStr = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
        const timeStr = `${pad(now.getHours())}${pad(now.getMinutes())}`;
        return `员工信息_${dateStr}_${timeStr}.xlsx`;
      }
      if (!this.ids.length) {
        this.$message.warning('请选择数据')
        return
      }
      this.$request.post('/staff/export', this.ids, {
        responseType: 'blob',
        response: true
      }).then(res => {
        const blob = new Blob([res.data], {
          type: res.headers['content-type'] || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        const disposition = res.headers['content-disposition'];   // 拿到原始头
        const fileName = extractFileName(disposition);
        saveAs(blob, fileName);
      }).catch(err => {
        console.error(err);
      });
    },
    reset() {
      this.username = null
      this.name = null
      this.load(1)
    },
    handleCurrentChange(pageNum) {
      this.load(pageNum)
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.load(this.pageNum)
    },
    handleAvatarSuccess(response, file, fileList) {
      // 把头像属性换成上传的图片的链接
      this.form.avatar = response.data
    },
  }
}
</script>

<style scoped>

</style>